package com.xin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xin.entity.SOrg;
import com.xin.mapper.SOrgDao;
import com.xin.service.SOrgService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 学校组织 服务实现类
 * </p>
 *
 * @author l1
 * @since 2017-12-05
 */
@Service
public class SOrgServiceImpl extends ServiceImpl<SOrgDao, SOrg> implements SOrgService {

    @Override
    public JSONArray getTrees(List<Integer> checkedList) {

        JSONArray result = new JSONArray();
        //查询1级
        List<SOrg> firstOrgs = baseMapper.selectList(new EntityWrapper<SOrg>().eq("level", 1).orderBy("order_num", true));
        firstOrgs.forEach(sOrg -> {
            JSONObject tree = new JSONObject();
            tree.put("id",sOrg.getId());
            tree.put("pId",sOrg.getParentId());
            tree.put("name",sOrg.getName());
            if(checkedList!=null && checkedList.contains(sOrg.getId())){
                tree.put("checked",true);
            }
            result.add(tree);
            List<SOrg> childNodes = baseMapper.selectList(new EntityWrapper<SOrg>().eq("level", 2).eq("parent_id", sOrg.getId()).orderBy("order_num", true));
            childNodes.forEach(childOrg->{
                JSONObject child = new JSONObject();
                child.put("id",childOrg.getId());
                child.put("pId",childOrg.getParentId());
                child.put("name",childOrg.getName());
                if(checkedList!=null && checkedList.contains(childOrg.getId())){
                    child.put("checked",true);
                }
                result.add(child);
            });
        });
        return result;
    }
}
